<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ArrayBuffer对象</title>
</head>
<body>
    <h1>ArrayBuffer对象</h1>
    <h2>代表内存之中的一段二进制数据</h2>

    <script>
        // 创建ArrayBuffer
        const buffer = new ArrayBuffer(32); // 创建32字节的内存空间
        console.log(buffer.byteLength); // 32

        // 分配内存失败
        try {
            const buffer = new ArrayBuffer(Number.MAX_SAFE_INTEGER);
        } catch(e) {
            console.log('内存分配失败');
        }

        // 视图操作
        const int32View = new Int32Array(buffer);
        int32View[0] = 42;
        console.log(int32View[0]); // 42

        // ArrayBuffer.isView()
        console.log(ArrayBuffer.isView(int32View)); // true
        console.log(ArrayBuffer.isView(buffer)); // false

        // 实际应用示例
        // 1. 文件读取
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        document.body.appendChild(fileInput);

        fileInput.addEventListener('change', function() {
            const file = this.files[0];
            const reader = new FileReader();
            
            reader.onload = function() {
                const arrayBuffer = this.result;
                console.log('文件大小:', arrayBuffer.byteLength, '字节');
                
                // 处理二进制数据
                const view = new Uint8Array(arrayBuffer);
                console.log('前10个字节:', view.slice(0, 10));
            };
            
            reader.readAsArrayBuffer(file);
        });

        // 2. WebSocket二进制数据
        function handleBinaryMessage(arrayBuffer) {
            const view = new DataView(arrayBuffer);
            const value = view.getInt32(0); // 读取前4个字节
            console.log('接收到的值:', value);
        }

        // 3. 图像处理
        function createGrayscaleImage(width, height) {
            const buffer = new ArrayBuffer(width * height);
            const view = new Uint8Array(buffer);
            
            for (let i = 0; i < view.length; i++) {
                view[i] = Math.random() * 255; // 生成随机灰度值
            }
            
            return buffer;
        }
    </script>
</body>
</html> 